package com.masiyi.service;

import com.masiyi.spring.BeanPostProcessor;
import com.masiyi.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Description TODO
 * @Author masiyi
 * @Date 2023/1/16
 **/
@Component
public class OrderPostProcessor implements BeanPostProcessor {
    /**
     * 之前
     *
     * @param bean
     * @param beanName
     * @return
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    /**
     * 之后
     *
     * @param bean
     * @param beanName
     * @return
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {

        if (bean instanceof OrderService) {
            Object newProxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("运行切面逻辑");
                    return method.invoke(bean, args);
                }
            });
            return newProxyInstance;
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
